import {Dirs, FileSystem} from 'react-native-file-access';
import getUserDirsSystem from '@/fun/getUserDirsSystem';
import {round} from 'lodash';
import dayjs from 'dayjs';
export default async ({db, progress = () => {}}) => {
  try {
    const oldCount = await db.countAsync({});
    console.log('oldCount', oldCount, dayjs().format());
  } catch (e) {
    console.log('del.异常', e.message);
  }
  let sdCardPath = Dirs.SDCardDir;
  // sdCardPath = '/sdcard/电影';
  // sdCardPath = '/sdcard/img163';
  const rtList = await getUserDirsSystem({targetPath: sdCardPath});
  const newV = rtList[0]?.v;
  const total = rtList.length;
  let step = 20;
  if (total > 500) {
    step = 50;
  } else if (total > 5000) {
    step = 100;
  }
  for (let i = 0; i < total; i++) {
    const doc = rtList[i];
    try {
      await db.updateAsync(
        {path: doc.path},
        {$set: doc},
        {
          upsert: true,
        },
      );
      let p = round(((i + 1) / total) * 100, 2);
      // p = Math.max(1, p);
      if (i % step === 0 || i === 0) {
        progress({...doc, i: i + 1, t: total, p});
      }
    } catch (e) {
      console.log('异常', e.message);
    }
  }

  if (newV) {
    try {
      const delRes = await db.removeAsync(
        {type: 'directory', v: {$lt: newV}},
        {multi: true},
      );
      console.log('delRes', delRes);
      const newCount = await db.countAsync({});
      console.log('newCount', newCount, dayjs().format());
    } catch (e) {}
  }
};
